#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    vector<int> topu(vector<vector<int>>& g, vector<int>& d, int n) {
        queue<int>q;
        for (int i = 0; i < n; i++) {
            if (d[i] == 0)q.push(i);
        }
        while (!q.empty()) {
            auto it = q.front();
            q.pop();

            for (auto t : g[it]) {
                d[t]--;
                if (d[t] == 0) {
                    q.push(t);
                }
            }
        }
        vector<int> ans;
        for (int i = 0; i < n; i++) {
            if (d[i] == 0)ans.push_back(i);
        }
        return ans;
    }
    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
        int n = graph.size();
        vector<vector<int>> g(n);
        vector<int> d(n);
        for (int a = 0; a < n; a++) {
            for (auto b : graph[a]) {
                g[b].push_back(a);
            }
            d[a] = graph[a].size();
        }

        return topu(g, d, n);
    }
};